#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <cerrno>
#include <sys/types.h>
#include <sys/wait.h>

const int size = 1024;
std::string GetOtherMessage()
{
    static int cnt=0;
    std::string messageid = std::to_string(cnt);
    cnt++;
    pid_t pid = getpid();
    std::string stringpid = std::to_string(pid);
    std::string message = "messageid:";
    message += messageid;
    message += ",stringid:";
    message += stringpid;
    return message;
}

void SubProcessWrite(int wfd)
{
    int pipesieze=0;
    std::string message = "I am sun process.";
    while(true)
    {
        std::string info = message + GetOtherMessage();
        write(wfd,info.c_str(),info.size());
        sleep(2);
    }

}
void ParentProcessRead(int rfd)
{
    char buff[size];
    while(true)
    {
        int n = read(rfd,buff,sizeof(buff)-1);
        if(n > 0)
        {
            buff[n] = 0;
        }
        else if(n == 0)
        {
            std::cout<<"读到文件结束"<<std::endl;
            sleep(1);
        }
        std::cout << buff << std::endl;
    }

}
int main()
{
    // 1.创建管道
    int pipefd[2];
    int n = pipe(pipefd);
    if (n != 0)
    {
        std::cerr << "errno:" << errno << ":strerror:" << strerror(errno) << std::endl;
    }

    //2.创建子进程
    pid_t id = fork();
    if(id == 0)
    {
        //3.子进程进行写操作,先关闭读操作
        close(pipefd[0]);
        // SubProcessWrite(pipefd[1]);`
        close(pipefd[1]);  //可关可不关
        exit(0);
    }
    //3.父进程进行读操作
    close(pipefd[1]);
    ParentProcessRead(pipefd[0]);
    close(pipefd[0]);

    //等待子进程
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if(rid > 0)
    {
        std::cout << "wait child process done, exit sig: " << (status&0x7f) << std::endl;
        std::cout << "wait child process done, exit code(ign): " << ((status>>8)&0xFF) << std::endl;
    }
    return 0;
}
